package main

import (
	"code.google.com/p/log4go"
	"encoding/base64"
	"fmt"
	"git.oschina.net/cnjack/nightc-download/downloader"
	"github.com/Unknwon/goconfig"
	"net/http"
)

type Option struct {
	Port     string
	Savepath string
	SaveRule string
	LogPath  string
}

var option Option
var Dlist map[string]*downloader.Down
var logger log4go.Logger
var err error
var conf *goconfig.ConfigFile

func init() {
	//配置的读取
	ReadConfig()
	logger = InitLog(option.LogPath)
	downloader.LogInit(logger)
}

//TODO 下载列表
func main() {
	fmt.Println("downloader is running")
	fmt.Println("downloader's listening Port is " + option.Port)
	fmt.Println("downloader's SaveRule is " + option.SaveRule)
	fmt.Println("downloader's LogPath is " + option.LogPath)
	go logger.Info("Soft is Starting\r\t")
	http.HandleFunc("/", indexhandler)
	http.HandleFunc("/down", downhandler)
	http.HandleFunc("/tmp", tmphandler)
	http.ListenAndServe(":"+option.Port, nil)
}

func indexhandler(w http.ResponseWriter, req *http.Request) {
	WriteString(w, "welcome to use nightc-downloader")
}

//http://127.0.0.1:8081/down?url=aHR0cDovL3N1LmJkaW1nLmNvbS9zdGF0aWMvc3VwZXJwbHVzL2ltZy9sb2dvX3doaXRlX2VlNjYzNzAyLnBuZw==
func downhandler(w http.ResponseWriter, req *http.Request) {
	UrlBase64 := req.FormValue("url")
	UrlByte, err := base64.URLEncoding.DecodeString(UrlBase64)
	if err != nil {
		WriteString(w, err.Error())
	}
	dp, _ := downloader.DInit(string(UrlByte), option.SaveRule, option.Savepath, "")
	go logger.Info("Build Id\t" + dp.DId + "\tUrl\t" + dp.Url + "\r\n")
	go dp.Down()
	//等待返回
	Dlist[dp.DId] = dp
	if err == nil {
		WriteString(w, dp.DId)
	} else {
		WriteString(w, err.Error())
	}
}
func tmphandler(w http.ResponseWriter, req *http.Request) {
	UrlBase64 := req.FormValue("url")
	UrlByte, _ := base64.URLEncoding.DecodeString(UrlBase64)
	WriteString(w, string(UrlByte))
}
